#!/bin/bash
#sleep 120
sqlite_com="sqlite3 /home/pi/gps.sqlite"
mysql_com="mysql -u gps -pgps -D gps -e"
dbe=$(sqlite3 /home/pi/gps.sqlite "select max(epoch) from GPS_TTY;")
if [ -z "$dbe" ]; then
	echo Anlegen TTY-Tabelle
	${sqlite_com} "create table GPS_TTY (uid integer,tty text,utc bigint,idvendor text,idmodel text,baud integer,path text);"
fi
if [ $(mysql -u gps -pgps -D gps -e "select * from information_schema.tables where table_schema='gps' and table_name='GPS_TTY';"|wc -l) -eq 0 ]; then
	${mysql_com} "create table gps.gpstty (uid smallint unsigned,tty text,utc bigint unsigned,idvendor text,idmodel text,baud mediumint unsigned,path text);"
fi

for i in /dev/ttyACM*; do
  if [ $(udevadm info -a -q property --export -n $i|grep GNSS|wc -l) -gt 1 ]; then
    TTY=$(echo $i|cut -d/ -f3)
    uid=$(echo $(udevadm info --name=${i}|sed -n '/MAJOR/{s/[A-Z: =]*//;p}')*256+$(udevadm info --name=/dev/${TTY}|sed -n '/MINOR/{s/[A-Z: =]*//;p}')|bc)
   idp=$(udevadm info -a -q property --export -n $i|grep ID_MODEL_ID|cut -d= -f2|sed -e "s/'//g")
   idv=$(udevadm info -a -q property --export -n $i|grep ID_VENDOR_ID|cut -d= -f2|sed -e "s/'//g")
   idpath=$(udevadm info -a -q property --export -n $i|grep ID_PATH=|cut -d= -f2|sed -e "s/'//g")
   echo $(date +%s),${TTY},${idp},${idv},$i
   ${sqlite_com} "insert into GPS_TTY (uid,tty,utc,idvendor,idmodel,baud,path) values (${uid},'${TTY}',$(date +%s),'${idp}','${idv}',$(stty -F ${i} speed),'${idpath}');"
   ${mysql_com} "insert into gpstty (uid,tty,utc,idvendor,idmodel,baud,path) values (${uid},'${TTY}',$(date +%s),'${idp}','${idv}',$(stty -F ${i} speed),'${idpath}');"
   nohup /home/pi/gps/gps_raw5.sh ${TTY} &>/dev/null &
  fi
done

